package com.wiseman.writing;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.wiseman.writing.utility.database.WDatabase;

public class FragmentSupport {

	public static class GradeFragment extends Fragment implements OnClickListener, ConstValue {

		int btIDs[] = { R.id.btKinderGarden, R.id.btGrade1A, R.id.btGrade1B, R.id.btGrade2A, R.id.btGrade2B,
				R.id.btGrade3A, R.id.btGrade3B, R.id.btGrade4A, R.id.btGrade4B, R.id.btGrade5A, R.id.btGrade5B,
				R.id.btGrade6A, R.id.btGrade6B, };

		String eventType[] = { "wc_class_preschool", "wc_class_one", "wc_class_two", "wc_class_three", "wc_class_four",
				"wc_class_five", "wc_class_six", };

		/**
		 * Create a new instance of CountingFragment, providing "num" as an
		 * argument.
		 */
		public static GradeFragment newInstance(int num) {
			GradeFragment f = new GradeFragment();

			Bundle args = new Bundle();
			f.setArguments(args);

			return f;
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

			View v = inflater.inflate(R.layout.grade_activity, container, false);

			Button bt = null;

			for (int i = 0; i < btIDs.length; i++) {
				bt = (Button) v.findViewById(btIDs[i]);
				bt.setOnClickListener(this);
				bt.setTag(i);
			}

			return v;
		}

		@Override
		public void onClick(View v) {

			int id = (Integer) v.getTag();
			String event = id == 0 ? eventType[0] : eventType[(id - 1) / 2 + 1];
			MobclickAgent.onEvent(getActivity(), event);

			Intent intent = new Intent();
			intent.setClass(getActivity(), StudyActivity.class);
			intent.putExtra(GRADE_ID, id);

			startActivity(intent);
		}

	}

	public static class UserDefinedFragment extends Fragment implements OnClickListener, ConstValue {

		ArrayList<String> mData = new ArrayList<String>();
		private ItemAdapter mAdapter;
		private EditText mEdChars;

		int mDataLen = 0;

		/**
		 * Create a new instance of CountingFragment, providing "num" as an
		 * argument.
		 */
		public static UserDefinedFragment newInstance(int num) {
			UserDefinedFragment f = new UserDefinedFragment();

			// Supply num input as an argument.
			Bundle args = new Bundle();
			f.setArguments(args);

			return f;
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			getData();
		}

		final String NAME = "SUD";
		final String LENTH = "lenth";

		void getData() {
			SharedPreferences sp = getActivity().getSharedPreferences(PREF_USER_DEFINED, 0);
			mDataLen = sp.getInt(LENTH, 0);

			for (int i = 0; i < mDataLen; i++) {
				String item = sp.getString(NAME + i, "");
				mData.add(item);
			}

		}

		void commitData(String data, int id) {
			SharedPreferences sp = getActivity().getSharedPreferences(PREF_USER_DEFINED, 0);
			Editor ed = sp.edit();
			ed.putString(NAME + id, data);
			ed.putInt(LENTH, id + 1);
			ed.apply();
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

			View v = inflater.inflate(R.layout.mylist_button, container, false);

			mEdChars = (EditText) v.findViewById(R.id.edChars);

			Button btAdd = (Button) v.findViewById(R.id.btAdd);
			btAdd.setOnClickListener(this);

			ListView mList = (ListView) v.findViewById(android.R.id.list);

			mAdapter = new ItemAdapter(getActivity(), mData);

			mList.setTextFilterEnabled(true);

			mList.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					// When clicked, show a toast with the TextView text
					// Toast.makeText(getActivity(), ((TextView)
					// view).getText(), Toast.LENGTH_SHORT).show();

					Intent intent = new Intent();
					intent.setClass(getActivity(), StudyActivity.class);
					intent.putExtra(GRADE_ID, GRADE_USER_DEFIND);
					intent.putExtra(INTENTNAME_CHARLIST, ((TextView) view).getText());

					startActivity(intent);

				}
			});

			mList.setAdapter(mAdapter);
			return v;
		}

		@Override
		public void onClick(View v) {
			String chars = mEdChars.getText().toString();

			StringBuilder sb = new StringBuilder();
			if (chars != null && !chars.isEmpty()) {
				Pattern p = Pattern.compile("\\p{InCJK Unified Ideographs}");
				Matcher m = p.matcher(chars);

				while (m.find()) { // Find each match in turn; String can't do
									// this.
					String str = m.group();
					sb.append(str);
					System.out.println(m.group());
				}
			}

			if (sb.length() > 0) {

			//	TreeSet<Character> sets = new TreeSet<Character>();
			//	for (int i = 0; i < sb.length(); i++) {
			//		sets.add(sb.charAt(i));
			//	}

				//String item = new String();
			//	for (char c : sets) {
				//	item += c;
			//	}
				String item = sb.toString();
				mData.add(0, item);
				commitData(item, mDataLen);
				mDataLen++;
				mEdChars.setText("");
				mAdapter.notifyDataSetChanged();
			}

		}

	}

	public static class ItemAdapter extends BaseAdapter {

		List<String> mData;
		Context mContext;

		public ItemAdapter(Context context, List<String> data) {
			mContext = context;
			mData = data;
		}

		@Override
		public int getCount() {

			return mData.size();
		}

		@Override
		public Object getItem(int position) {

			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View view = null;

			if (convertView == null) {
				LayoutInflater mInflater = LayoutInflater.from(mContext);
				view = mInflater.inflate(R.layout.listitem, parent, false);
			} else {
				view = convertView;
			}

			setItem(view, position);

			return view;
		}

		void setItem(View v, int pos) {

			int bgColor = v.getResources().getColor(
					pos % 2 == 0 ? R.color.list_background1 : R.color.list_background2);

			v.setBackgroundColor(bgColor);
			String chars = mData.get(pos);
			if (chars != null) {
				TextView tvData = (TextView) v.findViewById(R.id.list_date);
				tvData.setText(String.format("%02d", pos));
				
				GridView gv = (GridView) v.findViewById(R.id.list_chars);
				CharsAdapter adapter = new CharsAdapter(mContext, chars, true);
				gv.setAdapter(adapter);
				gv.setOnItemClickListener(adapter);
			}

		}

	}

	// history.
	public static class HistoryFragment extends Fragment implements ConstValue {

		private ArrayList<StrokeDBData> mDataList = new ArrayList<StrokeDBData>();
		private WDatabase mDatabase = null;
		private WriteRecoadAdapter mAdapter;

		/**
		 * Create a new instance of CountingFragment, providing "num" as an
		 * argument.
		 */
		public static HistoryFragment newInstance(int num) {
			HistoryFragment f = new HistoryFragment();

			// Supply num input as an argument.
			Bundle args = new Bundle();
			f.setArguments(args);

			return f;
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			mDatabase = new WDatabase(getActivity(), TABLE_NAME) {
				@Override
				public void fillKeys() {
					mKeyMap.put(KEY_CHARS, "TEXT");
				}
			};

			mDatabase.open();

			loadData();
		}

		@Override
		public void onResume() {		
			
			if(mAdapter != null){
				if(mDataList != null){
					mDataList.clear();
				}
				
				loadData();				
				mAdapter.dataChange(mDataList);
			}
			

			super.onResume();
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

			View v = inflater.inflate(R.layout.list, container, false);
			ListView lv = (ListView) v.findViewById(android.R.id.list);
			TextView tv = (TextView) v.findViewById(android.R.id.empty);
			if (mDataList.isEmpty()) {
				lv.setVisibility(View.GONE);
				tv.setVisibility(View.VISIBLE);
			} else {
				mAdapter = new WriteRecoadAdapter(getActivity(), mDataList);
				lv.setAdapter(mAdapter);
			}

			DomoAd.createBar(v);

			return v;
		}

		@Override
		public void onDestroy() {
			mDatabase.close();
			super.onDestroy();
		}

		private void loadData() {

			Cursor c = mDatabase.fetchAllData();

			while (c.moveToNext()) {
				StrokeDBData data = new StrokeDBData();
				data.getData(c);
				mDataList.add(data);
			}

			c.close();
		}

		class WriteRecoadAdapter extends BaseAdapter {

			ArrayList<StrokeDBData> mData = null;
			Context mContext = null;

			public WriteRecoadAdapter(Context context, ArrayList<StrokeDBData> data) {
				mContext = context;
				mData = data;
			}

			public void dataChange(ArrayList<StrokeDBData> data) {
				mData = data;
				notifyDataSetChanged();
			}

			@Override
			public int getCount() {
				return mData.size();
			}

			@Override
			public Object getItem(int arg0) {
				return mData.get(arg0);
			}

			@Override
			public long getItemId(int arg0) {
				return arg0;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {

				View view = null;

				if (convertView == null) {
					LayoutInflater mInflater = LayoutInflater.from(mContext);
					view = mInflater.inflate(R.layout.listitem, parent, false);
				} else {
					view = convertView;
				}

				setItem(view, position);

				return view;
			}

			void setItem(View v, int pos) {

				int bgColor = getResources().getColor(
						pos % 2 == 0 ? R.color.list_background1 : R.color.list_background2);

				v.setBackgroundColor(bgColor);
				StrokeDBData data = mData.get(pos);
				if (data != null) {
					TextView tvData = (TextView) v.findViewById(R.id.list_date);
					tvData.setText(data.toDateString());

					GridView gv = (GridView) v.findViewById(R.id.list_chars);
					CharsAdapter adapter = new CharsAdapter(mContext, data.mChars, true);
					gv.setAdapter(adapter);
					gv.setOnItemClickListener(adapter);
				}

			}
		}

	}

	// favor.
	public static class FavorFragment extends Fragment implements ConstValue {

		/**
		 * Create a new instance of CountingFragment, providing "num" as an
		 * argument.
		 */
		public static FavorFragment newInstance(int num) {
			FavorFragment f = new FavorFragment();

			// Supply num input as an argument.
			Bundle args = new Bundle();
			f.setArguments(args);

			return f;
		}

		GridView mGridView;
		private String mCharsList = new String();
		CharsAdapter mAdapter = null;

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
		}

		@Override
		public void onResume() {
			mCharsList = AppUtil.getFavorData(getActivity());
			mAdapter.updateData(mCharsList);
			super.onResume();
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

			View v = inflater.inflate(R.layout.study_activity, container, false);
			mCharsList = AppUtil.getFavorData(v.getContext());
			mAdapter = new CharsAdapter(v.getContext(), mCharsList, false);

			mGridView = (GridView) v.findViewById(R.id.gvChars);
			mGridView.setAdapter(mAdapter);
			mGridView.setOnItemClickListener(mAdapter);

			DomoAd.createBar(v);
			return v;
		}
	}

}
